import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import joblib
from tqdm import tqdm  # 导入tqdm库

# 加载数字数据集
digits = datasets.load_digits()

# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, random_state=42)

# 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_accuracy = 0
best_k = 0
best_knn_model = None

# 初始化一个列表以存储每个k值的准确率
accuracies = []

# 使用tqdm创建进度条
for k in tqdm(range(1, 41), desc='Training KNN models'):
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    predictions = knn.predict(X_test)
    accuracy = accuracy_score(y_test, predictions)
    accuracies.append(accuracy)
    if accuracy > best_accuracy:
        best_accuracy = accuracy
        best_k = k
        best_knn_model = knn

# 将最佳KNN模型保存到二进制文件
joblib.dump(best_knn_model, 'best_knn_model.pkl')

# 打印最佳准确率和相应的k值
print(f"Best Accuracy: {best_accuracy} with k={best_k}")

# 绘制准确率与k值的关系图
plt.figure(figsize=(10, 6))
plt.plot(range(1, 41), accuracies, color='blue', label='Accuracy')  # 为线条添加标签
plt.axvline(x=best_k, color='red', linestyle='-', label='Best k')  # 为垂直线添加标签
plt.scatter(best_k, best_accuracy, color='red', label='Best Accuracy')  # 为点添加标签
plt.text(best_k, best_accuracy, f'(k={best_k}, Accuracy={best_accuracy:.2f})', color='red', fontsize=12)  # 添加标签
plt.title('KNN Accuracy for Different k Values')
plt.xlabel('k Value')
plt.ylabel('Accuracy')
plt.legend()  # 现在这里有标签可以显示了
plt.grid(True)
plt.savefig('accuracy_plot.pdf')
plt.show()
